// 本模块为首页视图相关逻辑及状态,主要用来做页面传参
import news from '@/api/news.js'

const state = {
    newsList: [],
    newsPageTotal: 1,
    newsLastPage: 1,
    newsDetails: {},
    newsCategory: []
}

const getters = {
    newsList(state) {
        return state.newsList
    },
    newsPageTotal(state) {
        return state.newsPageTotal
    },
    newsLastPage(state) {
        return state.newsLastPage
    },
    newsDetails(state) {
        return state.newsDetails
    },
    newsCategory(state) {
        return state.newsCategory
    },
}

const mutations = {
    setNewsState(state, { key, value }) {
        state[key] = value
    },
}
const actions = {
    getNewsList({ state, dispatch, commit }, data) {
        return new Promise((resolve, reject) => {
            news.news({
                per_page: data.per_page,
                page: data.page,
                category_id: data.category_id,
            }).then((res) => {
                let code = res.data.code;
                if (code == 200) {
                    commit('setNewsState', {
                        key: 'newsList',
                        value: res.data.data.data
                    }),
                        commit('setNewsState', {
                            key: 'newsPageTotal',
                            value: res.data.data.total
                        }),
                        commit('setNewsState', {
                            key: 'newsLastPage',
                            value: res.data.data.last_page
                        })
                    resolve(res)
                }
            }).catch((error) => {
                reject(error)
            });
        })
    },
    getNewsDetails({ state, dispatch, commit }, data) {
        return new Promise((resolve, reject) => {
            news.newsDetails(data.id).then((res) => {
                let code = res.data.code;
                if (code == 200) {
                    commit('setNewsState', {
                        key: 'newsDetails',
                        value: res.data.data
                    })
                }
                resolve(res)
            }).catch((error) => {
                reject(error)
            });
        })
    },
    getNewsCategory({ state, dispatch, commit }, data) {
        return new Promise((resolve, reject) => {
            news.newsCategory().then((res) => {
                let code = res.data.code;
                if (code == 200) {
                    commit('setNewsState', {
                        key: 'newsCategory',
                        value: res.data.data
                    })
                }
                resolve(res)
            }).catch((error) => {
                reject(error)
            });
        })
    },
}
export default {
    state,
    getters,
    actions,
    mutations
}